package com.dreamchaser.familydevice.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisHandleUtil {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource(name = "singletaskExecutor")
    ExecutorService executorService;

    //region redis操作
    //设置缓存
    public boolean setObject(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
        return true;
    }

    //设置缓存和过期时间
    public boolean setObject(String key, Object value, Integer seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public Object getObject(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    //判断是否存在key
    public boolean isHasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    //删除缓存
    public boolean removeKey(String key) {
        redisTemplate.delete(key);
        return true;
    }
    //endregion

    /*================================================== 设置缓存 ================================================*/
    public boolean setObjectLock(String key, Object value,long time) {
        return redisTemplate.opsForValue().setIfAbsent(key, value,time,TimeUnit.SECONDS);
    }


    /*================================================== 异步设置缓存 ================================================*/
    //异步设置缓存
    public void setObjectByAsync(String key, Object value, long l, TimeUnit timeUnit) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    redisTemplate.opsForValue().set(key, value, l, timeUnit);
                } catch (Exception e) {
                    log.error("redis异步设置异常:" + key, e);
                }

            }
        });
    }

    /**
     * 异步插入string数据
     *
     * @param key
     * @param value
     * @param n
     * @param timeUnit
     */
    public void setStringByAsync(String key, String value, long n, TimeUnit timeUnit) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    stringRedisTemplate.opsForValue().set(key, value, n, timeUnit);
                } catch (Exception e) {
                    log.error("redis异步设置异常", e);
                }

            }
        });

    }



}
